import dayjs from "dayjs";
import {
  DeletePlanTemplatePermissions,
  PlanTemplatePermissionsGetPageData,
  PlanTemplatePermissionsAddOrUpdate,
  PlanTemplatePermissionsGetAddOrUpdateBaseData
} from "@/api/admin/teacher";
import { type PaginationProps } from "@pureadmin/table";
import { storageLocal } from "@pureadmin/utils";
import { sessionKey, type DataInfo } from "@/utils/auth";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import qs from "qs";

export function useAuthority() {
  const dataList = ref();
  const planName = ref("");
  const loading = ref(false);
  const isdisabled = ref(false);
  const addDtoRef = ref();
  const updatePanelVisible = ref(false);
  const loadingTitle = ref("添加");
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const isplanTemplateId = ref();
  const form = reactive<any>({
    planTemplatePermissionsId: "",
    planTemplateId: "",
    isDelete: 1,
    isEdit: 1,
    creatorId: "",
    isPublicTemplate: 0,
    userId: ""
  });

  const columns = [
    {
      label: "排序",
      type: "index",
      minWidth: 100
    },
    {
      label: "教师账号",
      prop: "userId"
    },
    {
      label: "教师姓名",
      prop: "userName"
    },
    {
      label: "计划名称",
      prop: "planName",
      minWidth: 120
    },
    {
      label: "修改时间",
      prop: "modificationTime"
    },
    {
      label: "创建时间",
      prop: "createTime"
    },
    {
      label: "公共模板",
      cellRenderer: ({ row }: any) => (
        <span>
          {
            row.isPublicTemplate == 1 ? "是" : "否"
          }
        </span>
      )
    },
    {
      label: "任务类型",
      cellRenderer: ({ row }: any) => (
        <span>
          {
            row.type == 1 ? "实训模式" : "竞赛模式"
          }
        </span>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  // 修改-添加
  async function handleUpdate(row) {
    if (!row) {
      loadingTitle.value = "添加";
      isdisabled.value = false;
    } else {
      loadingTitle.value = "修改";
      isdisabled.value = true;
      nextTick(() => {
        form.planTemplatePermissionsId = row.planTemplatePermissionsId;
        form.planTemplateId = isplanTemplateId.value.find(
          item => item.planId == row.planId
        );
        form.creatorId = row.creatorId;
        form.userId = row.userId;
        form.isDelete = row.isDelete;
        form.isEdit = row.isEdit;
        form.isPublicTemplate = row.isPublicTemplate
        isdisabled.value = true;
      });
    }
    updatePanelVisible.value = true;
  }
  // 删除
  async function handleDelete(row) {
    ElMessageBox({
      title: "提示", //MessageBox 标题
      closeOnClickModal: false,
      message: "是否确定删除当前项?", //MessageBox 消息正文内容
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        const res = await DeletePlanTemplatePermissions(
          qs.stringify({
            planTemplatePermissionsId: row.planTemplatePermissionsId
          })
        );
        if (res.success) {
          ElMessage.success(res.msg);
          onSearch();
        } else {
          ElMessage.error(res.msg);
        }
      })
      .catch(() => { });
  }

  // 保存数据
  async function handSave(row) {
    if (form.planTemplateId == "") {
      ElMessage.warning("请选择计划模板");
      return;
    }
    const data = {
      planTemplatePermissionsId: form.planTemplatePermissionsId,
      planTemplateId: form.planTemplateId.planId,
      isDelete: form.isDelete,
      isEdit: form.isEdit,
      isPublicTemplate: form.isPublicTemplate,
      creatorId: storageLocal().getItem(sessionKey)['username'],
      userId: form.planTemplateId.teacherAccount
    };
    const res = await PlanTemplatePermissionsAddOrUpdate(data);
    if (res.success) {
      ElMessage.success(res.msg);
      onSearch();
      ClosePanelVisible(row);
    } else {
      ElMessage.error(res.msg);
    }
  }

  // 搜索
  async function onSearch() {
    const data = {
      pageindex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planName: planName.value
    };
    const res = await PlanTemplatePermissionsGetPageData(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount;
      loading.value = false;
    } else {
      ElMessage.error(res.msg);
    }
  }

  function ClosePanelVisible(row) {
    updatePanelVisible.value = false;
    // form.planTemplatePermissionsId = "";
    // form.planTemplateId = "";
    // form.permissionType = 1;
    // form.creatorId = "";
    // form.userId = "";
    // form.isPublicTemplate = ""
    row.resetFields();
  }

  // 获取计划模板
  async function GetAddOrUpdateBaseData() {
    const res = await PlanTemplatePermissionsGetAddOrUpdateBaseData();
    if (res.success) {
      isplanTemplateId.value = res?.data;
    } else {
      ElMessage.error(res.msg);
    }
  }

  function handleSizeChange(val: number) {
    onSearch();
  }

  function handleCurrentChange(val: number) {
    onSearch();
  }

  onMounted(() => {
    onSearch();
    GetAddOrUpdateBaseData();
  });
  return {
    form,
    dataList,
    loading,
    columns,
    planName,
    pagination,
    addDtoRef,
    isdisabled,
    loadingTitle,
    updatePanelVisible,
    isplanTemplateId,
    handSave,
    onSearch,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange
  };
}
